package Common

import (
	"archive/zip"
	"github.com/axgle/mahonia"
	_"github.com/axgle/mahonia"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
)

//压缩文件
//files 文件数组，可以是不同dir下的文件或者文件夹
//dest 压缩文件存放地址
func Compress(files []*os.File, dest string) error {
	d, _ := os.Create(dest)
	defer d.Close()
	w := zip.NewWriter(d)
	defer w.Close()
	for _, file := range files {
		err := compress(file, "", w)
		if err != nil {
			return err
		}
	}
	return nil
}

func compress(file *os.File, prefix string, zw *zip.Writer) error {
	info, err := file.Stat()
	if err != nil {
		return err
	}
	if info.IsDir() {
		prefix = prefix + "/" + info.Name()
		fileInfos, err := file.Readdir(-1)
		if err != nil {
			return err
		}
		for _, fi := range fileInfos {
			f, err := os.Open(file.Name() + "/" + fi.Name())
			if err != nil {
				return err
			}
			err = compress(f, prefix, zw)
			if err != nil {
				return err
			}
		}
	} else {
		header, err := zip.FileInfoHeader(info)
		header.Name = prefix + "/" + header.Name
		if err != nil {
			return err
		}
		writer, err := zw.CreateHeader(header)
		if err != nil {
			return err
		}
		_, err = io.Copy(writer, file)
		file.Close()
		if err != nil {
			return err
		}
	}
	return nil
}

//解压
func DeCompress(zipFile, dest string) error {
	reader, err := zip.OpenReader(zipFile)
	if err != nil {
		return err
	}
	defer reader.Close()
	//log.Println("create dir MkdirAll:",getDir(dest))
	err = os.MkdirAll(dest, 0755)
	if err != nil {
		log.Println("create dir error:",err)
		return err
	}
	for _, file := range reader.File {
		rc, err := file.Open()
		if err != nil {
			return err
		}
		defer rc.Close()
		//filename := dest
		//if file.Flags == 0{
		//	filename=filename+string(ConvertToByte(file.Name, "gbk", "utf-8"))
		//}else{
		//	filename=filename+file.Name
		//}

		filename := dest + file.Name
		log.Println(filename)
		err = os.MkdirAll(getDir(filename), 0755)
		if err != nil {
			log.Println("create dir in zip error:",err)
			return err
		}
		w, err := os.Create(filename)
		if err != nil {
			return err
		}
		defer w.Close()
		_, err = io.Copy(w, rc)
		if err != nil {
			return err
		}
		err= w.Close()
		if err!=nil{
			return  err;
		}
		err=rc.Close()
		if err!=nil{
			return  err;
		}
	}
	return nil
}

//这里写一个转码的公共方法 params
//src 需要转码的字符串
//srcCode 字符串原编码格式
//targetCode 字符串需要转成的目标格式
func ConvertToByte(src string, srcCode string, targetCode string) []byte {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(src)
	tagCoder := mahonia.NewDecoder(targetCode)
	_, targetSrc, _ := tagCoder.Translate([]byte(srcResult), true)
	return targetSrc
}

func getDir(path string) string {
	return subString(path, 0, strings.LastIndex(path, string(filepath.Separator)))
}

func subString(str string, start, end int) string {
	rs := []rune(str)
	length := len(rs)

	if start < 0 || start > length {
		panic("start is wrong")
	}

	if end < start || end > length {
		panic("end is wrong")
	}

	return string(rs[start:end])
}
